// 创建用户相关的小仓库
import { defineStore } from "pinia";
// 引入token相关的方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token.ts";
// 引入类型
import type { UserState } from "@/store/modules/types/type";
// 引入请求
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
// 引入常量路由
import { constantRoutes, asyncRoutes, anyRoutes } from "@/router/routes.ts";

import cloneDeep from "lodash/cloneDeep";
import {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from "@/api/user/type.ts";
import router from "@/router";

// 递归过滤异步路由表
const filterAsyncRoutes = (routes: any, userRoutes: any) => {
  return routes.filter((item: any) => {
    if (userRoutes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        // 过滤孩子 使得孩子中只保留有权限的路由
        item.children = filterAsyncRoutes(item.children, userRoutes);
      }
      return true;
    }
  });
};

let useUserStore = defineStore("User", {
  state: (): UserState => ({
    token: GET_TOKEN(),
    menuRoutes: constantRoutes,
    username: "",
    avatar: "",
    buttons: [],
  }),
  getters: {
    // 获取用户名
  },
  actions: {
    // 登录
    async userLogin(data: loginFormData) {
      // 发送请求
      let result: loginResponseData = await reqLogin(data);
      if (result.code == 200) {
        // 保存token
        SET_TOKEN(result.data as string);
        return "ok";
      } else {
        return Promise.reject(new Error("登录失败"));
      }
    },
    // 获取用户信息
    async userInfo() {
      let resultUserInfo: userInfoResponseData = await reqUserInfo();
      if (resultUserInfo.code == 200) {
        this.username = resultUserInfo.data.name;
        this.avatar = resultUserInfo.data.avatar;
        let userRoutes = filterAsyncRoutes(
          cloneDeep(asyncRoutes),
          resultUserInfo.data.routes,
        );
        // 将过滤后的路由保存到menuRoutes中  用于渲染菜单
        this.menuRoutes = [...constantRoutes, ...userRoutes, ...anyRoutes];
        // console.log(this.menuRoutes)
        // 将过滤后的路由添加到路由表中 用于路由跳转
        this.menuRoutes.forEach((item: any) => {
          router.addRoute(item);
        });
        // 保存按钮权限  用于按钮的显示隐藏
        this.buttons = resultUserInfo.data.buttons;
        // console.log(router.getRoutes())
        return "ok";
      } else {
        return Promise.reject(new Error("获取用户信息失败"));
      }
    },
    // 退出登录
    async userLogout() {
      //1. 发送请求 通知服务器退出登录
      let resultLogout: any = await reqLogout();
      if (resultLogout.code == 200) {
        //2. 清空store的token
        this.token = "";
        this.menuRoutes = [];
        this.username = "";
        this.avatar = "";
        //3. 清空本地的用户信息
        REMOVE_TOKEN();
        //4. 跳转到登录页面
        return "ok";
      } else {
        return Promise.reject(new Error("退出登录失败"));
      }
    },
  },
});

export default useUserStore;
